
<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width,minimum-scale=1.0,maximum-scale=1.0,user-scalable=no"/>
    <meta name="description" content="道可道二维码在线生成器利用了HTML5最新IndexedDB本地缓存技术,是专门为Web开发人员精心设计开发的方便快捷的二维码生成工具" />
    <meta name="keywords" content="道可道,二维码,二维码图片,二维码制作,QR code,二维码生成,二维条码,微信二维码" />
    <title>道可道二维码在线生成器</title>
    <link rel="stylesheet" href="vendor/bootstrap/dist/css/bootstrap.min.css"/>
    <link rel="stylesheet" href="vendor/bootstrap/dist/css/bootstrap-theme.min.css"/>
    <link rel="stylesheet" href="vendor/bootstrap3-dialog/dist/css/bootstrap-dialog.min.css"/>
    <style>
        .container{
            background-color:#ececec;
        }

        .table > tbody > tr > td {
            word-break: break-all;
        }

        .table tr td:nth-child(1) {
            width: 50px;
        }

        .table tr td:nth-child(4) {
            width: 40px;
        }

        .table tr td:nth-child(3) {
            width: 100px;
        }

        .header {
            background-color: #61c2d0;
            height: 60px;
            line-height: 60px;
            margin-bottom: 20px;
            font-size: large;
            color: #fff;
        }

        .container {
            background-color: #fff;
        }

        .col-lg-8{
            position:relative;
        }

        .form-row{
            position:absolute;
            z-index: 1;
            left:15px;
            right:15px;
        }

        .table.table-striped{
            margin-top: 150px;
        }

        .form-row.fixed1 {
            position: fixed;
            top: 0;
            z-index: 1;
            -position: absolute;
            -top: expression(eval(document.documentElement.scrollTop));
        }

        .qrcode-panel.fixed2 {
            position: fixed;
            top: 0;
            z-index: 1;
            -position: absolute;
            -top: expression(eval(document.documentElement.scrollTop));
        }

        .col-lg-4 .panel {
            height: 291px;
        }

        .qrcode-panel{
            position:absolute;
            /*right:15px;*/

        }
        .col-lg-8{
            min-height:2000px;
        }

        @media (max-width: 768px) {
            .col-center-block {
                float: none;
                display: block;
                margin-left: auto;
                margin-right: auto;
            }
            .qrcode-panel{
                position: static;
                width: 291px;
                /*right: 0;*/


                float: none;
                display: block;
                margin-left: auto;
                margin-right: auto;

            }
            .qrcode-panel-container{
                text-align: center;



            }
            .form-row{
                /*top:0px;*/
            }

            .form-row.fixed1 {
                position:static;
            }

            .qrcode-panel.fixed2 {
                position: static;
            }

        }
    </style>

    <script>
        var _hmt = _hmt || [];
        (function() {
            var hm = document.createElement("script");
            hm.src = "//hm.baidu.com/hm.js?6796bd898032c363a6c8b88ae32dafe7";
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(hm, s);
        })();
    </script>


</head>
<body>
<div class="container">

    <div class="header col-lg-12">道可道二维码</div>
    <div class="row">
        <div class="col-lg-4 col-md-4 col-sm-5 col-xs-12 qrcode-panel-container">
            <div id="qrcode-panel" class="panel panel-default qrcode-panel">
                <div class="panel-body text-center">
                    <div id="output"><canvas width="256" height="256"></canvas></div>
                </div>
            </div>
        </div>

        <div class="col-lg-8 col-md-8 col-sm-7 col-xs-12">
            <div id="form-row" class="panel panel-default form-row">
                <div class="panel-heading">敲回车可保存URL<button id="delete-all" class="btn btn-default btn-xs pull-right">删除所有历史URLs</button></div>
                <div class="panel-body">
                    <form action="">
                        <textarea class="form-control" name="" id="" placeholder="请在这里粘贴或编辑网址 "></textarea>
                    </form>
                </div>
            </div>


            <table class="table table-striped">
                <thead>
                <tr>
                    <th>#</th>
                    <th>URL</th>
                    <th>Datetime</th>
                    <th></th>
                </tr>
                </thead>
                <tbody id="url-list"></tbody>
            </table>
        </div>
    </div>
</div>





<script src="vendor/jquery/dist/jquery.min.js"></script>
<script src="vendor/jquery-qrcode/jquery.qrcode.min.js"></script>
<script src="vendor/bootstrap/dist/js/bootstrap.min.js"></script>
<script src="vendor/bootstrap3-dialog/dist/js/bootstrap-dialog.min.js"></script>
<!--<script src="vendor/node-uuid/uuid.js"></script>-->
<script>

    $(function () {
        /*
         * 吸顶灯
         * option {
         *    fixCls: className，默认 “fixed”
         *    fixedFunc: 吸顶时回调函数
         *    resetFunc: 不吸顶时回调函数
         * }
         */
        $.fn.topSuction = function(option) {
            option = option || {}
            var fixCls = option.fixCls || 'fixed'
            var fixedFunc = option.fixedFunc
            var resetFunc = option.resetFunc

            var $self = this
            var $win  = $(window)
            if (!$self.length) return

            var offset = $self.offset()
            var fTop   = offset.top
            var fLeft  = offset.left
            var fWidth = $self.width();

            // 暂存
            $self.data('def', offset)
            $win.resize(function() {
                $self.data('def', $self.offset());
                if(window.innerWidth > 768){
                    window.location.href = 'http://dkd.cn';
                    //console.log(window.innerWidth);
                }
            })

            $win.scroll(function() {
                if(window.innerWidth > 768){
                    var dTop = $(document).scrollTop()
                    if (fTop < dTop) {
                        $self.addClass(fixCls)
                        $self.css({"left":fLeft,"width":fWidth});
                        if (fixedFunc) {
                            fixedFunc.call($self, fTop)
                        }
                    } else {
                        $self.removeClass(fixCls).removeAttr('style')

                        if (resetFunc) {
                            resetFunc.call($self, fTop)
                        }
                    }
                }

            })
        };

        $('#form-row').topSuction({"fixCls":"fixed1"})
        $('#qrcode-panel').topSuction({"fixCls":"fixed2"})

    })

    //定义全局变量和函数
    var db;
    window.indexedDB = window.indexedDB || window.webkitIndexedDB || window.mozIndexedDb ||window.window.msIndexedDB;
    function dtFormat(input) {
        if (!input) return "";
        var res = (input.getMonth() + 1) + "-" + input.getDate() + " ";
        var hour = input.getHours();
        var minute = input.getMinutes() + 1;
        if (minute < 10) minute = "0" + minute;
        res += hour + ":" + minute;
        return res;
    }


    //替换所有的回车换行.用在富文本编辑器时可以把""换成"<br>"
    function trimStr(str) {
        str = str.replace(/\n/g, "");
        str = str.replace(/\r/g, "");
        str = str.replace(" ","");
        return str;
    }


    $(function () {


        var $urlList = $('#url-list');
        var $textarea = $('textarea');
        var isExtend = false;

        $textarea.on('input propertychange', function () {
            generateQRCode();
        }).focus().on('focus', function () {
            $(this)[0].select();
        }).on('dblclick', function () {
            if(!isExtend){
                $(this).attr('rows',10);
                isExtend = true;
            }else{
                $(this).removeAttr('rows');
                isExtend = false;
            }

        }).on('blur',function(){
            $(this).removeAttr('rows');
        });

        function generateQRCode() {
            $('#output').html("").qrcode(trimStr($textarea.val()));
        }

        if (!window.indexedDB) {
            BootstrapDialog.show({
                title: '提示',
                message: '您的浏览器不支持IndexedDB,将无法在本地保存历史数据,建议使用Safari,Chrome或火狐浏览器以达到最佳体验效果!',
                buttons: [{
                    label: 'Close',
                    action: function (dialog) {
                        dialog.close();
                    }
                }]
            });
        return;
        }



        //操作IndexedDB
        var openRequest = window.indexedDB.open('url', 6);

        //错误处理
        openRequest.onerror = function (e) {
//        console.log("Error opening db");
//        console.dir(e);
        };

        //
        openRequest.onupgradeneeded = function (e) {
            var thisDb = e.target.result;
            var objectStore;
//        console.log(thisDb);

            //Create url OS
            if (!thisDb.objectStoreNames.contains("url")) {
//            console.log("I need to make the url objectstore");
                objectStore = thisDb.createObjectStore("url", {keyPath: "id", autoIncrement: true});
                objectStore.createIndex('url', 'url', {unique: true});
            }

        };

        openRequest.onsuccess = function (e) {
//        console.log('onsuccess');
            db = e.target.result;

            db.onerror = function (event) {
                // Generic error handler for all errors targeted at this database's
                // requests!
//            console.log("Database error: " + event.target.errorCode);
//            console.dir(event.target);
            };

            displayUrls();

        };


        function displayUrls() {

            var transaction = db.transaction(["url"], "readonly");
            var content = "";

            var handleResult = function (event) {
                var cursor = event.target.result;
                if (cursor) {

                    content += '<tr>' +
                            '<td>' + cursor.key + '</td>' +
                            '<td> ' + decodeURIComponent(cursor.value.url) + '</td>' +
                            '<td>' + dtFormat(cursor.value.updated) + '</td>' +
                            '<td>' +
                            '<button class="btn btn-danger btn-xs"><i class="glyphicon glyphicon-trash"></i></button>' +
                            '</td>' +
                            '</tr>';

                    cursor.continue();
                }
                else {
                    content += '';
                }

                $urlList.html(content);
            };


            var objectStore = transaction.objectStore("url");

            //'prev'参数相当DESC
            objectStore.openCursor(null, 'prev').onsuccess = handleResult;
            transaction.oncomplete = function (event) {
                $urlList.html(content);
            };


        }

        // save URL
        $textarea.on("keyup", function (e) {
            if (e.keyCode == 13) {
                var url = trimStr($textarea.val());
                $textarea.val(url);
                url = encodeURIComponent(url);
                if (url == "") {
                    BootstrapDialog.show({
                        title: '提示',
                        message: '网址不可为空!',
                        buttons: [{
                            label: 'Close',
                            action: function (dialog) {
                                dialog.close();
                            }
                        }]
                    });

                } else {
                    var t = db.transaction(['url'], 'readwrite');
                    var saveRequest = t.objectStore("url").add({url: url, updated: new Date()});
                    saveRequest.onerror = function () {
                        var errorMessage = saveRequest.error.message;
                        if (errorMessage.indexOf('uniqueness') > -1) {

                            BootstrapDialog.show({
                                title: '提示',
                                message: 'URL地址重复!',
                                buttons: [{
                                    label: 'Close',
                                    action: function (dialog) {
                                        dialog.close();
                                    }
                                }]
                            });

                        }
                    }
                    t.oncomplete = function () {
                        displayUrls();
                    };

                    return false;

                }


            }

        });




        //给URL列表行添加点击事件
        $('#url-list').on('click', 'tr', function () {
            var url = $(this).find('td:nth-child(2)').text();
            url = trimStr(url);
            $('#output').html("").qrcode(url);
            $('textarea').val(url);
            $(this).css('background-color', 'yellow').siblings().css('background-color', '');
        })

        //添加删除列表行事件
        $('#url-list').on('click', '.btn-danger', function (e) {
            e.preventDefault();
            var urlId = $(this).parent().prev().prev().prev().html();
//        console.log(urlId)


            var t = db.transaction(["url"], "readwrite");
//        console.log(t);
            var request = t.objectStore("url").delete(parseInt(urlId));
            t.oncomplete = function (e) {
                displayUrls();
            };
            return false;

        })

        //delete all event
        $('#delete-all').on('click',function(){
            BootstrapDialog.show({
                title: '再次确认',
                message: '是否删除所有历史URL ?',
                buttons: [{
                    label: 'Cancel',
                    action: function(dialogItself){
                        dialogItself.close();
                    }
                }, {
                    label: 'OK',
                    cssClass: 'btn-primary',
                    action: function(dialogItself) {
                        deleteAllHistoryData(dialogItself);
                    }
                }]
            });
        })

        function deleteAllHistoryData(dialogItself){
            //删除数据库前必须先关闭数据库，否则不能成功删除，会导致错误
            db.close();

            if(window.indexedDB.webkitGetDatabaseNames){
                window.indexedDB.webkitGetDatabaseNames().onsuccess = function(sender,args){
                    var len = sender.target.result.length;

                    if(len >0){

                        window.indexedDB.deleteDatabase('url');
                        $urlList.html('');
                    }
                }
            }else{
                window.indexedDB.deleteDatabase('url');
                $urlList.html('');
            }

            dialogItself.close();
            location.reload();


        }


    })


</script>

</body>
</html>
